﻿/**
 * Copyright (c) 2013 Jeremy Wyman
 * Microsoft Public License (Ms-PL)
 * This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
 * 1. Definitions
 *    The terms "reproduce", "reproduction", "derivative works", and "distribution" have the same meaning here as under U.S. copyright law.
 *    A "contribution" is the original software, or any additions or changes to the software.
 *    A "contributor" is any person that distributes its contribution under this license.
 *    "Licensed patents" are a contributor's patent claims that read directly on its contribution.
 * 2. Grant of Rights
 *    (A) Copyright Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
 *    (B) Patent Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
 * 3. Conditions and Limitations
 *    (A) No Trademark License - This license does not grant you rights to use any contributors' name, logo, or trademarks.
 *    (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
 *    (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
 *    (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
 *    (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 *    
 * More info on: http://tempest.codeplex.com
**/

using System;
using System.Collections.Generic;
using System.Threading;

namespace Tempest.Collections
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <remarks>When enumerated using a foreach loop a copy of all data is made for thread-safety</remarks>
    [System.Diagnostics.DebuggerDisplay("Map<{typeof(TKey)}, {typeof(TValue)}>.Count = {Count}")]
    public sealed class Map<TKey, TValue> : IDictionary<TKey, TValue>
    {
        public Map()
        {
            _dictionary = new Dictionary<TKey, TValue>();
        }
        public Map(int capacity)
        {
            _dictionary = new Dictionary<TKey, TValue>(capacity);
        }
        public Map(IEqualityComparer<TKey> comparer)
        {
            _dictionary = new Dictionary<TKey, TValue>(comparer);
        }
        public Map(int capacity, IEqualityComparer<TKey> comparer)
        {
            _dictionary = new Dictionary<TKey, TValue>(capacity, comparer);
        }

        public event Action<Map<TKey, TValue>, UpdatedEventArgs<TKey, TValue>> Updated;

        private Dictionary<TKey, TValue> _dictionary;
        private bool _isReadOnly;
        private ReaderWriterLockSlim _lock;

        public int Count { get { return _dictionary.Count; } }
        public bool IsReadOnly { get { return _isReadOnly; } }
        public ICollection<TKey> Keys
        {
            get
            {
                TKey[] keys;
                _lock.EnterReadLock();
                try
                {
                    keys = new TKey[_dictionary.Count];
                    int i = 0;
                    foreach (TKey key in _dictionary.Keys)
                    {
                        keys[i] = key;
                    }
                }
                catch { throw; }
                finally
                {
                    _lock.ExitReadLock();
                }
                return keys;
            }
        }
        public ICollection<TValue> Values
        {
            get
            {
                TValue[] values;
                _lock.EnterReadLock();
                try
                {
                    values = new TValue[_dictionary.Count];
                    int i = 0;
                    foreach (TValue value in _dictionary.Values)
                    {
                        values[i] = value;
                    }
                }
                catch { throw; }
                finally
                {
                    _lock.ExitReadLock();
                }
                return values;
            }
        }

        public TValue this[TKey key]
        {
            get
            {
                if (key == null)
                    throw new ArgumentNullException("key");
                //
                _lock.EnterReadLock();
                try
                {
                    if (!_dictionary.ContainsKey(key))
                        throw new KeyNotFoundException("key is not found in the map");
                    //
                    return _dictionary[key];
                }
                catch { throw; }
                finally
                {
                    _lock.ExitReadLock();
                }
            }
            set
            {
                if (key == null)
                    throw new ArgumentNullException("key");
                if (_isReadOnly)
                    throw new InvalidOperationException("The Map is read-only and cannot be ammended");
                //
                _lock.EnterWriteLock();
                try
                {
                    if (!_dictionary.ContainsKey(key))
                        throw new KeyNotFoundException("key is not found in the map");
                    _dictionary[key] = value;
                }
                catch { throw; }
                finally
                {
                    _lock.ExitWriteLock();
                }
            }
        }

        public void Add(TKey key, TValue value)
        {
            if (key == null)
                throw new ArgumentNullException("key");
            if (_isReadOnly)
                throw new InvalidOperationException("The Map is read-only and cannot be ammended");
            //
            _lock.EnterWriteLock();
            try
            {
                if (_dictionary.ContainsKey(key))
                    throw new ArgumentException("The key is already present in the map");
                //
                _dictionary.Add(key, value);
            }
            catch { throw; }
            finally
            {
                _lock.ExitWriteLock();
            }
            this.OnUpdate(UpdatedEventType.ElementAdded, key, value);
        }

        public void Clear()
        {
            KeyValuePair<TKey, TValue>[] elements;
            //
            _lock.EnterWriteLock();
            try
            {
                elements = new KeyValuePair<TKey, TValue>[_dictionary.Count];
                int i = 0;
                foreach (TKey key in _dictionary.Keys)
                {
                    elements[i] = new KeyValuePair<TKey, TValue>(key, _dictionary[key]);
                    i++;
                }
                //
                _dictionary.Clear();
            }
            catch { throw; }
            finally
            {
                _lock.ExitWriteLock();
            }
            //
            for (int i = 0; i < elements.Length; i++)
            {
                this.OnUpdate(UpdatedEventType.ElementRemoved, elements[i].Key, elements[i].Value);
            }
        }

        public bool ContainsKey(TKey key)
        {
            _lock.EnterReadLock();
            try
            {
                return _dictionary.ContainsKey(key);
            }
            catch { throw; }
            finally
            {
                _lock.ExitReadLock();
            }
        }

        public Map<TKey, TValue> GetChainedSurrogate()
        {
            Map<TKey, TValue> surrogate = new Map<TKey, TValue>() { _dictionary = _dictionary, _isReadOnly = true, _lock = _lock };
            this.Updated += surrogate.RouteEvents;
            return surrogate;
        }

        public Map<TKey, TValue> GetReadOnlyCopy()
        {
            return new Map<TKey, TValue>() { _dictionary = new Dictionary<TKey,TValue>(_dictionary), _isReadOnly = true };
        }

        public bool Remove(TKey key)
        {
            if (key == null)
                throw new ArgumentNullException("key");
            if (_isReadOnly)
                throw new InvalidOperationException("The Map is read-only and cannot be ammended");
            //
            bool success;
            KeyValuePair<TKey, TValue> element;
            //
            _lock.EnterWriteLock();
            try
            {
                element = new KeyValuePair<TKey, TValue>(key, _dictionary[key]);
                success = _dictionary.Remove(key);
            }
            catch { throw; }
            finally
            {
                _lock.ExitWriteLock();
            }
            //
            if (success)
            {
                this.OnUpdate(UpdatedEventType.ElementRemoved, element.Key, element.Value);
            }
            //
            return success;
        }

        private void RouteEvents(Map<TKey, TValue> sender, UpdatedEventArgs<TKey, TValue> args)
        {
            if (this.Updated != null)
            {
                this.Updated(this, args);
            }
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            if (key == null)
                throw new ArgumentNullException("key");
            //
            value = default(TValue);
            bool success = false;
            _lock.EnterReadLock();
            try
            {
                if (_dictionary.ContainsKey(key))
                {
                    value = _dictionary[key];
                }
            }
            catch { throw; }
            finally
            {
                _lock.ExitReadLock();
            }
            //
            return success;
        }

        private void OnUpdate(UpdatedEventType type, TKey key, TValue value)
        {
            if (this.Updated != null)
            {
                this.Updated(this, new UpdatedEventArgs<TKey, TValue>() { Key = key, Type = type, Value = value });
            }
        }

        #region void System.Collections.Generic.ICollection
        void System.Collections.Generic.ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> element)
        {
            this.Add(element.Key, element.Value);
        }

        void System.Collections.Generic.ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
        {
            if (array == null)
                throw new ArgumentNullException("array", "array cannot be null.");
            if (arrayIndex < 0)
                throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex must be greater than or equal to zero.");
            if (arrayIndex + _dictionary.Count > array.Length)
                throw new ArgumentException("The collection is too large to fit into the array.");
            //
            _lock.EnterReadLock();
            try
            {
                int i = arrayIndex;
                foreach (TKey key in _dictionary.Keys)
                {
                    array[i] = new KeyValuePair<TKey, TValue>(key, _dictionary[key]);
                    i++;
                }
            }
            catch { throw; }
            finally
            {
                _lock.ExitReadLock();
            }
        }

        bool System.Collections.Generic.ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> element)
        {
            bool contains = false;
            _lock.EnterReadLock();
            try
            {
                contains = _dictionary.ContainsKey(element.Key) && _dictionary[element.Key].Equals(element.Value);
            }
            catch { throw; }
            finally
            {
                _lock.ExitReadLock();
            }
            return contains;
        }

        bool System.Collections.Generic.ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> element)
        {
            return this.Remove(element.Key);
        }
        #endregion
        #region System.Collections.Generic.IEnumerable<KeyValuePair<TKey, TValue>>
        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
        {
            throw new NotImplementedException();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
        #endregion

        public struct UpdatedEventArgs<TKey, TValue>
        {
            public UpdatedEventType Type;
            public TKey Key;
            public TValue Value;
        }

        public enum UpdatedEventType
        {
            ElementAdded,
            ElementRemoved,
            ElementUpdated,
        }
    }
}
